import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Grid, Table, Pagination, Message, Dialog, Button, Balloon, Loading, Dropdown, Menu, Upload, Icon, Tag } from '@alifd/next';
import axios from 'axios'
import IceContainer from '@icedesign/container';
import TableFilter from './TableFilter';
import EditForm from './EditForm';
import IconSvg from '#/components/IconSvg';
import { ApiOfGatewayPage, ApiOfGatewayEnable, ApiOfGatewayDisable, ApiOfGatewayDelete, ApiOfGatewayExport } from '#/utils/coreApiDefine'
import { ApiOfGatewayTemplate, ApiOfGatewayImport } from '#/utils/coreApiDefine'
import SearchTableWrapper from '#/hoc/SearchTableWrapper'
import { inject } from 'mobx-react';
const { Row, Col } = Grid;

@inject('dictstore')
@SearchTableWrapper(ApiOfGatewayPage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      detailDialogVisible: false,
      editInstance: {},
      rowSelection: {
        onChange: this.onRowSelectChange.bind(this),
        selectedRowKeys: [],
        selectedRows: [],
      },
      actionBarLoadingVisible: false,
    };
  }

  renderStatus = (value, index, item) => {
    return (
      <Tag type="primary" color={item.disabled ? 'red' : 'green'} size="small">{item.disabled ? '已停用' : '已启动'}</Tag>
    )
  }

  renderBatched = (value, index, item) => {
    return (
      <Tag type="primary" color={item.batched ? 'red' : 'green'} size="small">{item.batched ? '是' : '否'}</Tag>
    )
  }

   renderName = (value, index, item) => {
    const linkProps = {
      to: "/manage/lowermachine/" + item.code + '/operation'
    };
    return (
      <Link {...linkProps}>{item.name}</Link>
    );
  }

  renderConfig = (value, index, item) => {
    let that = this;
    if (!item.config) {
      return (
        <div></div>
      );
    } else {
      let config = JSON.parse(item.config);
      return (
        <div>
          {Object.keys(config).map(function (k) {
            return (
              <dl style={that.props.styles.horizontal.dl} key={k}>
                <dt style={that.props.styles.horizontal.dt}>{k}</dt>
                <dd style={that.props.styles.horizontal.dd}>{config[k].toString()}</dd>
              </dl>
            );
          })}
        </div>
      );
    }
  }

  renderOper = (value, index, item) => {
    let that = this;

    const statusIcon = (item) => {
      let iconClass = "#icon-yunhang";
      if(!item.disabled) {
        iconClass = "#icon-tingzhi";
      }
      return iconClass;
    }

    const startStop = <Button title={item.disabled ? '启用' : '停用'} onClick={() => this.onToggleStatusConfirm(item)} type="primary" text style={{marginLeft: '5px'}}>
        <IconSvg iconClass={statusIcon(item)} style={{ width: '1.2em', height: '1.2em'}} />
      </Button>

    const edit = <Button title="编辑" onClick={() => this.onOpenDetailDialog(item)} type="primary" text style={{marginLeft: '5px'}}>
          <IconSvg iconClass="#icon-bianji" style={{ width: '1.2em', height: '1.2em'}} />
        </Button>

    const remove = <Button title="删除" onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text style={{marginLeft: '5px'}}>
          <IconSvg iconClass="#icon-shanchu" style={{ width: '1.2em', height: '1.2em'}} />
        </Button>

    return (
      <div>
        {startStop}
        {edit}
        {remove}
      </div>
    );
  }

  onDeleteConfirmOk = item => {
    return ApiOfGatewayDelete(item.code)
  }

  onToggleStatusConfirm = (item) => {
    let that = this;
    let Api = item.disabled ? ApiOfGatewayEnable : ApiOfGatewayDisable
    Dialog.confirm({
      title: '',
      content: '确认要' + (item.disabled ? '开启' : '停用') + '吗?',
      onOk: () => {
        Api(item.code).then(response => {
          that.props.fetch();
          Message.success('操作成功!');
        }).catch(function (error) {
          console.log(error);
        });
      }
    });
  }

  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }

  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  // 选择模式时，选择项改变事件
  onRowSelectChange(ids, records) {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    rowSelection.selectedRows = [...rowSelection.selectedRows, ...records]
    this.setState({ rowSelection });
  }

  onBatchDisableConfirm = (isDisabled) => {
    let that = this;
    Dialog.confirm({
      title: '',
      content: '确认要全部' + (isDisabled ? '停用' : '启用') + '吗?',
      onOk: () => {
        that.setState({
          actionBarLoadingVisible: true
        })
        let possibleRows = that.state.rowSelection.selectedRows,
          selectedRowKeys = that.state.rowSelection.selectedRowKeys;
        let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1 && !row.disabled === isDisabled)
          .filter((x, index, self) => self.indexOf(x) === index)
        let api = isDisabled ? ApiOfGatewayDisable : ApiOfGatewayEnable;
        axios.all(selectedRows.map(v => api(v.code)))
          .then(axios.spread(function () {
            const { rowSelection } = that.state;
            rowSelection.selectedRowKeys = [];
            rowSelection.selectedRows = []
            that.setState({
              rowSelection,
              actionBarLoadingVisible: false
            })
            that.props.fetch();
            Message.success('操作成功!');
          }));

      }
    });
  }

  beforeUpload = (info) => {
    //console.log('beforeUpload : ', info);
    if (info.size > 5242880) {
      Message.error('上传文件过大,超过5M；文件名：' + info.name);
      return false;
    }
    var ss = info.name.substr(info.name.lastIndexOf(".")).toLowerCase();
    if (ss != '.xlsx') {
      Message.error('文件格式不支持,请选择.xlsx的文件；文件名：' + info.name);
      return false;
    }
    Message.loading('上传文件中,请等待；文件名：' + info.name);
  }

  onSuccess = (info) => {
    var status = info.response.status;
    // console.log(info);
    if ('success' === status) {
      this.props.fetch();
      Message.show({
        type: 'success',
        title: '指标导入',
        duration: 5000,
        content: '导入成功：' + info.name
      });
    } else if ('failure' === status) {
      Message.show({
        type: 'error',
        title: '指标导入',
        duration: 10000,
        content: '导入失败，错误原因：' + info.response.errors[0].errmsg
      });
      this.props.fetch();
      return false;
    }
  }

  onError = (info) => {
    Message.error('导入失败，错误原因：' + info.response.errors[0].errmsg);
    return false;
  }

  renderPhysicalConnType = (value, index, item) => {
    let physicalConnTypeItem = this.props.dictstore.PhysicalConnTypeDS.find(item => item.value === value)
    return (
      <div>{physicalConnTypeItem.label}</div>
    );
  }

  renderWorkMode = (value, index, item) => {
    let workModeeItem = this.props.dictstore.ResourceWorkModeDS.find(item => item.value === value)
    return (
      <div>{workModeeItem.label}</div>
    );
  }
  exportData() {
    var that = this;
    var serarch = that.props.search;
    var url = ApiOfGatewayExport + '?';
    Object.keys(serarch).forEach(key => {
      if (serarch[key] != null) {
        url = url + key + '=' + serarch[key] + '&';
      }
    });
    fetch(url).then(res => res.blob().then(blob => {
      let a = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      let filename = res.headers.get('Content-disposition');
      if (filename) {
        filename = decodeURI(filename.split('=')[1]); //提取文件名
        a.href = url;
        a.download = filename; //给下载下来的文件起个名字
        a.click();
        window.URL.revokeObjectURL(url);
        a = null;
      }
    }));
  }

  render() {
    const { instances } = this.props.bindingData;
    return (
      <IceContainer style={this.props.styles.container}>
        <TableFilter
          filter={this.props.filter}
          create={this.onOpenDetailDialog.bind(this)}
          match={this.props.match}
        />

        <Row wrap gutter="20" style={styles.formRow}>
          <Col l="10">
            <div style={styles.formItem}>
              <Loading visible={this.state.actionBarLoadingVisible}>
                <div>
                  <Button onClick={this.onBatchDisableConfirm.bind(this, true)} disabled={this.state.rowSelection.selectedRowKeys.length == 0} size="small" type="normal">
                    全部停用
                  </Button>
                  <Button onClick={this.onBatchDisableConfirm.bind(this, false)} disabled={this.state.rowSelection.selectedRowKeys.length == 0} size="small" type="primary" style={{ 'marginLeft': '10px' }}>
                    全部启用
                  </Button>
                </div>
              </Loading>
              <form method="get" action={ApiOfGatewayTemplate}>
                <Button type="secondary" size="small" style={{ 'marginLeft': '10px' }} htmlType="submit">
                  <Icon type="download" />下载模版
                </Button>
              </form>
              <div>
                <Upload
                  action={ApiOfGatewayImport}
                  beforeUpload={this.beforeUpload}
                  onSuccess={this.onSuccess}
                  onError={this.onError}
                  multiple
                  accept='.xlsx'
                >
                  <Button title="导入网关模板数据" type="secondary" size="small" style={{ 'marginLeft': '10px' }}>
                    <Icon type="upload" />导入
                  </Button>
                </Upload>
              </div>
              <div>
                <Button title="导出网关数据" onClick={this.exportData.bind(this)} type="secondary" size="small" style={{ 'marginLeft': '10px' }}><Icon type="download" />导出</Button>
              </div>
              <Button onClick={() => this.onOpenDetailDialog()} size="small" type="secondary" style={{ 'marginLeft': '10px' }}><Icon type="add" />新建</Button>
            </div>
          </Col>
          <Col l="14">
            <Pagination
              style={{ 'marginBottom': '10px', ...this.props.styles.pagination, 'marginRight': '0' }}
              shape="arrow-only"
              pageSizeSelector="filter"
              current={this.props.page}
              total={instances.pageable.totalElements}
              totalRender={total => `总数: ${total}`}
              pageSize={instances.pageable.size}
              onChange={this.props.handlePaginationChange}
              onPageSizeChange={this.props.handlePageSizeChange}
            />
          </Col>
        </Row>
        <Table
          dataSource={instances.data}
          loading={this.props.loading}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
          onSort={this.props.handleSort}
          rowSelection={this.state.rowSelection}
        >
          <Table.Column width={160} title="名称" dataIndex="name" sortable={true} cell={this.renderName}  />
          <Table.Column width={140} title="编码" dataIndex="code" />
          <Table.Column width={90} title="网关类型" dataIndex="physicalConnType" cell={this.renderPhysicalConnType} sortable={true} />
          {/*<Table.Column width={90} title="工作模式" dataIndex="workMode" cell={this.renderWorkMode} sortable={true} />*/}
          <Table.Column
            width={240}
            title="配置信息"
            sortable={true}
            dataIndex="config"
            cell={this.renderConfig}
          />
          <Table.Column width={90} title="绑定资源数" dataIndex="resourceSize" />
          <Table.Column
            width={80}
            title="状态"
            dataIndex="disabled"
            cell={this.renderStatus}
            sortable={true} />
          <Table.Column
            width={80}
            title="批量采集"
            dataIndex="batched"
            cell={this.renderBatched} />
          <Table.Column
            width={80}
            title="集群节点"
            dataIndex="node" />
          <Table.Column
            width={100}
            title="操作"
            cell={this.renderOper}
          />
        </Table>
        <Pagination
          style={this.props.styles.pagination}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Dialog
          style={{ width: '50%' }}
          title="网关设置"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
};